package com.aplink.generic.xmlparser;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.text.TextUtils;

import com.aplink.generic.constant.FormDesignConstant;
import com.aplink.generic.constant.type.SharePreferenceType;
import com.aplink.generic.pojo.formdesign.Column;
import com.aplink.generic.pojo.formdesign.InitValue;

public class InitValueParser {

	private static final String DEFAULT_VALUE = "defaultValue";
	private static final String INIT_VALUE = "initValue";
	private static final String PASSED_COLUMN_ID = "passedColumnID";
	private static final String SHARE_PREFERENCE_VALUE = "SharePreferenceValue";

	public static InitValue parseInitValue(Node node) {
		final InitValue initValue = new InitValue();
		Element element = (Element) node;
		NodeList nodes = element
		        .getElementsByTagName(InitValueParser.INIT_VALUE);
		if (nodes.getLength() == 0) {
			return initValue;
		}
		node = nodes.item(0);
		if (node.getNodeType() == Node.ELEMENT_NODE) {
			element = (Element) node;
			nodes = element.getElementsByTagName(FormDesignConstant.COLUMN);
			for (int i = 0; i < nodes.getLength(); i++) {
				final Column column = new Column();
				final Node nodeColumn = nodes.item(i);
				if (nodeColumn.hasAttributes()) {
					String value = XmlPaserUtil.getAttrValue(nodeColumn,
					        InitValueParser.SHARE_PREFERENCE_VALUE);
					if (!TextUtils.isEmpty(value)) {
						column.setPreferenceType(SharePreferenceType.get(value));
					}

					value = XmlPaserUtil.getAttrValue(nodeColumn,
					        InitValueParser.DEFAULT_VALUE);
					if (!TextUtils.isEmpty(value)) {
						column.setDefaultValue(value);
					}

					value = XmlPaserUtil.getAttrValue(nodeColumn,
					        InitValueParser.PASSED_COLUMN_ID);
					if (!TextUtils.isEmpty(value)) {
						column.setPassedColumnID(value);
					}
				}
				final String columnValue = XmlPaserUtil
				        .getNodeValue(nodeColumn);
				column.setColumnName(columnValue);
				initValue.add(column);
			}
		}
		return initValue;
	}
}
